package org.javapicalc;
import java.util.*;
import org.deuce.*;

public class Method<T, S>{
	protected HashMap<Channel, Method> Connections = new HashMap<Channel, Method>();
	@Atomic
	public Boolean addConnection(Channel c, Method x){
		//if both connections of c are non null return false
		if(this.Connections.get(c) == null){
			this.Connections.put(c,x);
			if(x.isConnected(c))
				return true;
			else{
				x.addConnection(c, this);
				return true;
			}
		}
		return false;
	}
	
	@Atomic
	public Boolean isConnected(Channel c){
		if(this.Connections.get(c) == null) return false;
		return true;
	}
	@Atomic
	public Boolean removeConnection(Channel c){
		if(this.Connections.remove(c) != null) return true;
		return false;
	}
	
	//revisit synchronisation 
//	@Atomic
//	public void Send(Channel c, Integer msg){
//		long current = System.currentTimeMillis();
//		long future = current+3000;
//		while(!c.ready){
//			current = System.currentTimeMillis();
//			future = current+1000;
//			while(System.currentTimeMillis() < future){}
//		}
//		c.send(msg);
//	}
	@Atomic
	public void Send(Channel c, Method p){
		Method x = this.Connections.get(c);
		this.removeConnection(c);
		p.addConnection(c, x);
	}
	
	public void Send(Channel c, Channel x, Channel y){
		while(!c.ready){
			
		}
		c.send(x, y);
	}
	public void Send(Channel<T, S> c, T x, S y){
		while(!c.ready){
			
		}
		c.send(x, y);
	}
	@Atomic
	public void Receive(Channel c, Channel x, Channel y){
		while(c.ready){
			//wait for the msg
		}
		c.receive(x, y);
	}
	@Atomic
	public void Receive(Channel<T, S> c, T x, S y){
		while(c.ready){
			
		}
		c.receive(x, y);
	}
	
}